#每天清理redis key LOG_DEVICE_ACTIVE_   LOG_NEW_DEVICE_ACTIVE_  LOG_DEVICE_NEW_ACTIVE_V3_ZJKJ_  LOG_DEVICE_NEW_SHOW_ZJKJ_
import redis
import datetime
import pymysql

from dbutils.pooled_db import PooledDB

# redis
def getReidsConnection():
    redis_info = {
        "host": "172.20.151.90",
        "password": "Coocaa2022",
        "port": 6379,
        "db": 8
    }

    r = redis.Redis(**redis_info, decode_responses=True)
    return r


# 删除历史key
#redisKey 为需要删除的key day 天数 表示删除多少天之前的key
def deleteAllByKeyName(redisKey,day):
    r = getReidsConnection()
    keys = r.keys()
    date7 = getdate(day)
    print(f"日期为:{date7}")
    for key in keys:
        if key.__contains__(f'{redisKey}'):
            day = key[-8:]
            if(int(day)<int(date7)):
                print(f"{key}数量为:{r.scard(key)}")
                r.delete(key)
                print(f"删除{key}成功")


# 删除历史key  LOG_DEVICE_ACTIVE_V1_ZJKJ
#serId 为服务 day 天数 天数 表示删除多少天之前的key   executeFlag执行标志 0:不需要执行 1:需要执行
def deleteAllKey(serId,day,executeFlag):
    r = getReidsConnection()
    if executeFlag == 1:
        # redis key
        redisStr = 'V1'
    else:
        redisStr = 'V2'
    keys = r.keys()
    date7 = getdate(day)
    print(f"日期为:{date7}")
    for key in keys:
        if key.__contains__(f'LOG_DEVICE_ACTIVE_{serId}'):
            day = key[-8:]
            if(int(day)<int(date7)):
                print(f"{key}数量为:{r.scard(key)}")
                r.delete(key)
                print(f"删除{key}成功")
    for key in keys:
        if key.__contains__(f'LOG_DEVICE_NEW_ACTIVE_{serId}'):
            day = key[-8:]
            if(int(day)<int(date7)):
                print(f"{key}数量为:{r.scard(key)}")
                r.delete(key)
                print(f"删除{key}成功")

def deleteAllKeyMain():
    deleteAllKey('ZJKJ', 8, 1)
    deleteAllKey('YJYL', 8, 1)
    deleteAllKey('JKZX', 8, 1)
    deleteAllKey('ZJTX', 8, 1)
    deleteAllKey('ZJKJ', 8, 0)

#将指定字符串 dateStr ,偏移 offsetInt 天后再输出字符串
#如 20220805 偏移7天 即增加7天后 输出 20220812
def strToTime(dateStr,offsetInt):
    t = datetime.datetime.strptime(dateStr, "%Y%m%d")
    #print(t)
    offset = datetime.timedelta(days=offsetInt)
    re_date = (t+offset).strftime('%Y%m%d')
    #print(re_date)
    return  re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    return re_date

if __name__ == '__main__':
    toDay = getdate(1)
    beforeDay = getdate(2)
    deleteAllKeyMain()
    #deleteAllByKeyName("LOG_DEVICE_NEW_ACTIVE_V3_ZJKJ_",3)
    #deleteAllByKeyName("LOG_DEVICE_NEW_SHOW_ZJKJ_",3)




